<template>
  <view class="container">
    <!-- 模式切换 -->
    <view class="mode-switch">
      <button 
        :class="['mode-btn', activeMode === 'solar' ? 'active' : '']" 
        @click="activeMode = 'solar'"
      >公历</button>
      <button 
        :class="['mode-btn', activeMode === 'lunar' ? 'active' : '']" 
        @click="activeMode = 'lunar'"
      >农历</button>
    </view>

    <!-- 日期选择 -->
    <view class="date-picker">
      <picker 
        mode="date" 
        :value="selectedDate" 
        :start="getMinDate()"
        :end="getMaxDate()"
        @change="handleDateChange"
      >
        <view class="picker-input">
          {{ selectedDate || '请选择出生日期' }}
        </view>
      </picker>
    </view>

    <!-- 查询按钮 -->
    <button class="query-btn" @click="handleQuery">立即查询</button>

    <!-- 结果展示 -->
    <view v-if="result" class="result-card">

      <!-- 其他信息 -->
      <view class="info-item highlight">
        <text class="label">周岁</text>
        <view class="next-birthday-info">
          <text class="value" style="color: #fa3534;">{{ result.ageActual }}岁</text>
          <text class="value">周岁算法：每过一个生日就长一岁。</text>
        </view>
      </view>
      <view class="info-item highlight">
        <text class="label">虚岁</text>
        <view class="next-birthday-info">
          <text class="value" style="color: #fa3534;">{{ result.ageNominal }}岁</text>
          <text class="value">虚岁算法：一出生就是一岁，然后每过一个春节就长一岁。</text>
        </view>
      </view>
      <view class="info-item">
        <text class="label">生肖</text>
        <text class="value">{{ result.zodiac }}</text>
      </view>
      <view class="info-item">
        <text class="label">星座</text>
        <text class="value">{{ result.constellation }}</text>
      </view>

      <!-- 基本信息 -->

      <view class="info-item highlight">
        <text class="label">公历出生日期</text>
        <view class="next-birthday-info">
          <text class="value">{{ result.solarBirthDate }}</text>
          <view class="value links-container">
            <text class="link-text" @click="navigateTo('/pages/index/birthday-code')">生日密码</text>
            <text class="separator">/</text> 
            <text class="link-text" @click="navigateTo('/pages/index/birthday-book')">生日书</text>
          </view>
        </view>
      </view>
      <view class="info-item highlight">
        <text class="label">农历出生日期</text>
        <view class="next-birthday-info">
          <text class="value">{{ result.lunarBirthDate }}</text>
          <text class="value">（{{ result.ganZhi.year }}年 {{ result.ganZhi.month }}月 {{ result.ganZhi.day }}日）</text>
        </view>
      </view>
      

      <!-- 下次生日整合展示 -->
      <view class="info-item highlight">
        <text class="label">下次公历生日</text>
        <view class="next-birthday-info">
          <text class="value">距离下一次生日（{{ result.nextBirthday.date }}）</text>
          <text class="value">（剩余{{ result.nextBirthday.daysLeft }}天，那天是星期{{ result.nextBirthday.weekday }}）</text>
        </view>
      </view>
      
      <view class="info-item">
        <text class="label">生活天数</text>
        <text class="value">您在这个世界上生活了：{{ result.livedDays }} 天</text>
      </view>

      <!-- 人生进度条 -->
      <view class="progress-container">
        <text class="progress-label">人生进度（假设平均寿命是80岁）</text>
        <progress 
          :percent="result.lifeProgress" 
          stroke-width="8" 
          activeColor="#4393ff"
        />
        <text class="progress-percent">{{ result.lifeProgress }}%</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import lunarCalendar from 'lunar-calendar'; // 农历转换库

const activeMode = ref('solar');
const selectedDate = ref('');
const result = ref(null);

// 页面跳转函数
const navigateTo = (url) => {
  uni.navigateTo({
    url: url
  });
};

// 处理日期选择
const handleDateChange = (e) => {
  selectedDate.value = e.detail.value;
};

// 查询逻辑
const handleQuery = async () => {
  if (!selectedDate.value) {
    uni.showToast({ title: '请选择日期', icon: 'none' });
    return;
  }

  const birthDate = parseDate(selectedDate.value);
  const ganZhi = getGanZhi(birthDate.getFullYear(), birthDate.getMonth() + 1, birthDate.getDate());

  const resultData = {
    solarBirthDate: formatDate(birthDate),
    lunarBirthDate: getLunarBirthDate(birthDate),
    livedDays: calculateLivedDays(birthDate),
    nextBirthday: calculateNextBirthday(birthDate),
    ageActual: calculateActualAge(birthDate),
    ageNominal: calculateNominalAge(birthDate),
    zodiac: getZodiac(birthDate),
    constellation: getConstellation(birthDate),
    lifeProgress: calculateLifeProgress(birthDate),
    ganZhi: ganZhi
  };

  uni.setStorageSync('lastQuery', {
    mode: activeMode.value,
    date: selectedDate.value
  });

  result.value = resultData;
};

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}年${month}月${day}日`;
};

// 天干地支计算（国内传统方式）
const getGanZhi = (year, month, day) => {
  const gan = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
  const zhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];

  // 年干支计算
  const yearGanIndex = (year - 4) % 10;
  const yearZhiIndex = (year - 4) % 12;
  const yearGan = gan[yearGanIndex < 0 ? yearGanIndex + 10 : yearGanIndex];
  const yearZhi = zhi[yearZhiIndex < 0 ? yearZhiIndex + 12 : yearZhiIndex];

  // 月干支计算
  const monthGanIndex = (yearGanIndex * 2 + month) % 10;
  const monthZhiIndex = (month + 1) % 12;
  const monthGan = gan[monthGanIndex < 0 ? monthGanIndex + 10 : monthGanIndex];
  const monthZhi = zhi[monthZhiIndex < 0 ? monthZhiIndex + 12 : monthZhiIndex];

  // 日干支计算
  const baseDate = new Date(1900, 0, 31); // 1900年1月31日是甲子日
  const targetDate = new Date(year, month - 1, day);
  const daysDiff = Math.floor((targetDate - baseDate) / (1000 * 60 * 60 * 24));
  const dayGanIndex = daysDiff % 10;
  const dayZhiIndex = daysDiff % 12;
  const dayGan = gan[dayGanIndex < 0 ? dayGanIndex + 10 : dayGanIndex];
  const dayZhi = zhi[dayZhiIndex < 0 ? dayZhiIndex + 12 : dayZhiIndex];

  return {
    year: `${yearGan}${yearZhi}`,
    month: `${monthGan}${monthZhi}`,
    day: `${dayGan}${dayZhi}`
  };
};

// 获取农历出生日期（包含天干地支）
const getLunarBirthDate = (birthDate) => {
  const lunar = lunarCalendar.solarToLunar(
    birthDate.getFullYear(),
    birthDate.getMonth() + 1,
    birthDate.getDate()
  );
  
  if (lunar && lunar.lunarYear) {
    return `${lunar.lunarYear}年${lunar.lunarMonth}月${lunar.lunarDay}日`;
  }
  return '未知';
};

// 计算生活天数（包括今天）
const calculateLivedDays = (birthDate) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 设置时间为当天0点
  birthDate.setHours(0, 0, 0, 0); // 设置时间为当天0点
  const timeDiff = today - birthDate;
  return Math.floor(timeDiff / (1000 * 60 * 60 * 24)) + 1; // 包括今天
};

// 计算下次生日
const calculateNextBirthday = (birthDate) => {
  const today = new Date();
  const currentYear = today.getFullYear();
  const nextBirthday = new Date(currentYear, birthDate.getMonth(), birthDate.getDate());

  if (nextBirthday < today) {
    nextBirthday.setFullYear(currentYear + 1);
  }

  const daysLeft = Math.ceil((nextBirthday - today) / (1000 * 60 * 60 * 24));
  const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
  const weekday = weekdays[nextBirthday.getDay()];

  return {
    date: formatDate(nextBirthday),
    daysLeft,
    weekday
  };
};

// 实际年龄计算
const calculateActualAge = (birthDate) => {
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
};

// 虚岁计算
const calculateNominalAge = (birthDate) => {
  const today = new Date();
  const lunarNewYear = getLunarNewYear(today.getFullYear());
  return (today >= lunarNewYear) 
    ? today.getFullYear() - birthDate.getFullYear() + 1
    : today.getFullYear() - birthDate.getFullYear();
};

// 生肖计算
const getZodiac = (birthDate) => {
  const zodiacs = ['猴','鸡','狗','猪','鼠','牛','虎','兔','龙','蛇','马','羊'];
  const birthYear = birthDate.getFullYear();
  const lunarNewYear = getLunarNewYear(birthYear);
  return zodiacs[birthDate < lunarNewYear 
    ? (birthYear - 1) % 12 
    : birthYear % 12];
};

// 星座计算
const getConstellation = (birthDate) => {
  const month = birthDate.getMonth() + 1; // 月份（1-12）
  const day = birthDate.getDate(); // 日期（1-31）
  
  // 国内传统星座边界日期
  const constellations = [
    { name: '摩羯座', start: '12-22', end: '01-19' },
    { name: '水瓶座', start: '01-20', end: '02-18' },
    { name: '双鱼座', start: '02-19', end: '03-20' },
    { name: '白羊座', start: '03-21', end: '04-19' },
    { name: '金牛座', start: '04-20', end: '05-20' },
    { name: '双子座', start: '05-21', end: '06-21' },
    { name: '巨蟹座', start: '06-22', end: '07-22' },
    { name: '狮子座', start: '07-23', end: '08-22' },
    { name: '处女座', start: '08-23', end: '09-22' },
    { name: '天秤座', start: '09-23', end: '10-23' },
    { name: '天蝎座', start: '10-24', end: '11-22' },
    { name: '射手座', start: '11-23', end: '12-21' },
  ];
  
  const dateStr = `${month}-${day}`; // 格式化为MM-DD
  
  // 查找匹配的星座
  for (const constellation of constellations) {
    const start = constellation.start.split('-');
    const end = constellation.end.split('-');
    const startMonth = parseInt(start[0], 10);
    const startDay = parseInt(start[1], 10);
    const endMonth = parseInt(end[0], 10);
    const endDay = parseInt(end[1], 10);
  
    if (
      (month === startMonth && day >= startDay) ||
      (month === endMonth && day <= endDay) ||
      (startMonth > endMonth && (month > startMonth || month < endMonth))
    ) {
      return constellation.name;
    }
  }
  
  return '未知'
};

// 人生进度计算（修改版）
const calculateLifeProgress = (birthDate) => {
  const lifeExpectancy = 80;
  const livedYears = calculateActualAge(birthDate);
  const progress = Math.round((livedYears / lifeExpectancy) * 100);
  return progress; // 直接返回计算结果，不再限制最大值
};

// 农历转换
const parseDate = (dateString) => {
  if (activeMode.value === 'lunar') {
    const [year, month, day] = dateString.split('-').map(Number);
    const solarDate = lunarCalendar.lunarToSolar(year, month, day);
    return new Date(solarDate.year, solarDate.month - 1, solarDate.day);
  }
  return new Date(dateString);
};

// 获取农历新年日期
const getLunarNewYear = (year) => {
  const lunarNewYearMap = {
    2020: new Date(2020, 0, 25),
    2021: new Date(2021, 0, 12),
    2022: new Date(2022, 0, 1),
    2023: new Date(2023, 0, 22),
    2024: new Date(2024, 0, 10)
  };
  return lunarNewYearMap[year] || new Date(year, 0, 1);
};

// 添加获取最小日期的方法
const getMinDate = () => {
  return '1900-01-01';
};

// 添加获取最大日期的方法
const getMaxDate = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

onMounted(() => {
  const lastQuery = uni.getStorageSync('lastQuery');
  if (lastQuery) {
    activeMode.value = lastQuery.mode;
    selectedDate.value = lastQuery.date;
  }
});
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
  background-color: #f8f9fc;
  min-height: 100vh;

  .mode-switch {
    display: flex;
    margin: 30rpx 0;

    .mode-btn {
      flex: 1;
      margin: 0 10rpx;
      background-color: #ffffff;
      color: #606266;
      border-radius: 10rpx;
      font-size: 28rpx;
      transition: all 0.3s ease;
      box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
      height: 80rpx;
      line-height: 80rpx;

      &.active {
        background: linear-gradient(135deg, #4393ff, #2979ff);
        color: white;
        transform: scale(1.02);
      }
    }
  }

  .date-picker {
    margin: 30rpx 0;
    padding: 30rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    box-shadow: 0 6rpx 16rpx rgba(0,0,0,0.05);

    .picker-input {
      color: #303133;
      font-size: 28rpx;
      padding: 10rpx 0;
    }
  }

  .query-btn {
    background: linear-gradient(135deg, #4393ff, #2979ff);
    color: white;
    margin: 40rpx 0;
    border-radius: 10rpx;
    font-size: 32rpx;
    transition: all 0.3s ease;
    height: 90rpx;
    line-height: 90rpx;
    font-weight: 500;
    box-shadow: 0 6rpx 16rpx rgba(67, 147, 255, 0.2);

    &:active {
      transform: scale(0.98);
    }
  }

  .result-card {
    background-color: #ffffff;
    padding: 30rpx;
    border-radius: 16rpx;
    box-shadow: 0 6rpx 16rpx rgba(0,0,0,0.05);
    margin-bottom: 40rpx;

    .info-item {
      display: flex;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f7fa;
      font-size: 28rpx;

      &.highlight {
        background-color: #f8f9fc;
        margin: 10rpx -30rpx;
        padding: 20rpx 30rpx;
        border-radius: 8rpx;
      }

      .label {
        color: #606266;
        font-size: 28rpx;
      }

      .value {
        color: #303133;
        font-weight: 500;
        font-size: 28rpx;
      }
    }

    .progress-container {
      margin-top: 40rpx;
      padding: 30rpx;
      background-color: #f8f9fc;
      border-radius: 10rpx;

      .progress-label {
        font-size: 28rpx;
        color: #606266;
        margin-bottom: 20rpx;
        display: block;
      }

      .progress-percent {
        font-size: 28rpx;
        color: #4393ff;
        margin-top: 16rpx;
        text-align: right;
        display: block;
        font-weight: 500;
      }
    }

    .next-birthday-info {
      display: flex;
      flex-direction: column;
      align-items: flex-end;

      .value {
        font-size: 28rpx;
        color: #303133;
        font-weight: 500;

        &:last-child {
          font-size: 24rpx;
          color: #909399;
          margin-top: 8rpx;
          font-weight: 400;
        }
      }
    }

    .links-container {
      display: flex;
      align-items: center;
      
      .link-text {
        color: #4393ff;
        text-decoration: underline;
        font-size: 24rpx;
        font-weight: 400;
        
        &:active {
          opacity: 0.8;
        }
      }
      
      .separator {
        margin: 0 6rpx;
        color: #909399;
        font-size: 24rpx;
        font-weight: 400;
      }
    }
  }
}
</style>